package cn.pengyinrui.pethome.dept.service.impl;


import cn.pengyinrui.pethome.base.service.impl.BaseServiceImpl;
import cn.pengyinrui.pethome.dept.domain.Department;
import cn.pengyinrui.pethome.dept.mapper.DepartmentMapper;
import cn.pengyinrui.pethome.dept.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper mapper;

    @Override
    @Transactional
    public void add(Department department) {
        mapper.add(department);
        buildDirPath(department);
        mapper.update(department);
    }

    private void buildDirPath(Department department){
        if(department.getParent_id() == null){
            department.setDirPath("/"+department.getId());
        }else {
            department.setDirPath(mapper.findOne(department.getParent_id())
                    .getDirPath()
                    +"/"
                    +department.getId());
        }
    }


    @Override
    @Transactional
    public void update(Department department) {
        buildDirPath(department);
        mapper.update(department);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        System.out.println(mapper.findChildrenByIdCount(id));
        if (mapper.findChildrenByIdCount(id) != 0){
            throw new RuntimeException("下级部门不为空，无法删除");
        }
        mapper.delete(id);
    }

    @Override
    public List<Department> deptTree() {
        // 第一步：查询全部
        List<Department> departments = mapper.findAll();

        // 第二步：遍历依次将子类放入父类的children属性(list)中
        for (Department department : departments) {
            // 2.1如果有父类id，就说明是子类，拿到子类
            if(department.getParent_id() != null){
                for (Department department1 : departments) {
                    // 2.2第二次遍历，找到子类对应的父类，并将其放入父类的children集合中,并跳出循环
                    if (department.getParent_id() == department1.getId()){
                        department1.getChildren().add(department);
                        break;
                    }
                }
            }
        }

        /*List<Department> deptTree = departments.stream().filter(department -> {
            return department.getParent_id() == null;
        }).collect(Collectors.toList());*/

        // 第三步：找到最顶级的父类，将其放入部门树并返回，依层级可获取其子类
        return departments.stream()// 3.1开启线程，获取值
                .filter(department -> department.getParent_id() == null)// 3.2过滤器循环，取没有父类id的，顶级父类
                .collect(Collectors.toList());


    }
}
